package com.example.workflow.controller;

import com.example.workflow.entity.LeaveRequest;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

import org.flowable.task.api.Task;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Tag(name = "请假流程管理", description = "请假流程相关接口")
@RestController
@RequestMapping("/leave")
public class LeaveController {
    
    @Autowired
    private RuntimeService runtimeService;
    
    @Autowired
    private TaskService taskService;
    @Autowired
    private RepositoryService repositoryService;
    @Operation(summary = "启动请假流程", description = "创建一个新的请假申请流程")
    @PostMapping("/start")
    public String startLeaveProcess(@RequestBody LeaveRequest leaveRequest) {
        Map<String, Object> variables = new HashMap<>();
        variables.put("employee", leaveRequest.getUserId());
        variables.put("days", leaveRequest.getDays());
        variables.put("reason", leaveRequest.getReason());
        
        // 启动流程实例
        runtimeService.startProcessInstanceByKey("leaveProcess", variables);
        return "请假流程已启动";
    }

    @Operation(summary = "完成任务", description = "完成指定的任务并处理审批结果")
    @PostMapping("/task/{taskId}/complete")
    public String completeTask(@PathVariable String taskId, @RequestParam("approved") boolean approved) {
        Map<String, Object> variables = new HashMap<>();
        variables.put("approved", approved);
        taskService.complete(taskId, variables);
        return "任务已完成";
    }

    @GetMapping("/definitions")
    @Operation(summary = "获取流程定义列表")
    public List<Map<String, Object>> getProcessDefinitions() {
        return repositoryService.createProcessDefinitionQuery()
                .orderByProcessDefinitionVersion().desc()
                .list()
                .stream()
                .map(pd -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("id", pd.getId());
                    map.put("name", pd.getName());
                    map.put("key", pd.getKey());
                    map.put("version", pd.getVersion());
                    map.put("diagramUrl", "/process/diagram/" + pd.getId());
                    return map;
                })
                .collect(Collectors.toList());
    }

    @GetMapping("/instances/{processInstanceId}")
    @Operation(summary = "获取流程实例详情")
    public Map<String, Object> getProcessInstance(@PathVariable String processInstanceId) {
        Map<String, Object> result = new HashMap<>();
        // 获取流程实例
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                .processInstanceId(processInstanceId)
                .singleResult();
        if (processInstance != null) {
            result.put("processInstanceId", processInstance.getId());
            result.put("processDefinitionId", processInstance.getProcessDefinitionId());
            result.put("activityId", processInstance.getActivityId());
            // 获取当前任务
            List<Task> tasks = taskService.createTaskQuery()
                    .processInstanceId(processInstanceId)
                    .list();
            result.put("currentTasks", tasks);
        }
        return result;
    }
} 